import re

import requests
from bs4 import BeautifulSoup
from flask import jsonify, render_template, request, current_app
from information.utils.response_code import RET
from . import news_blu
from .. import data

@news_blu.route('/<int:news_id>',methods=['GET'])
def news_detail(news_id):
    from information.utils.models import News,CommentLike,User
    from information import db
    try:
        news=News.query.filter_by(id=news_id).first()
        #访问一下点击量增一
        news.clicks+=1
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询数据失败')
    data['news']=news.to_dict()
    comments=news.comments
    #查找新闻的作者
    data['news']['author'] = None
    author_id=news.user_id
    #print(author_id,type(author_id))
    if author_id:
        try:
            author = User.query.filter_by(id=author_id).first()
            data['news']['author']=author.to_dict()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库查询数据失败')
    if data['user']:
        #判断该用户是否已经关注了该新闻的作者
        if author_id:
            try:
                data['is_followed']=None
                user = User.query.filter_by(id=data['user']['id']).first()
                for followed in user.followers:
                    if followed.id==data['news']['author']['id']:
                        data['is_followed']=True
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR, errmsg='数据库查询数据失败')
        # 判断该用户是否已经收藏该新闻
        try:
            data['is_collected'] = None
            user = User.query.filter_by(id=data['user']['id']).first()
            for collection in user.collection_news:
                #print(collection.id, news_id)
                if collection.id == news_id:
                    data['is_collected'] = True
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库查询数据失败')
        # 找到所有当前用户点过赞的评论
        try:
            comment_likeds=CommentLike.query.filter_by(user_id=data['user']['id']).all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库查询数据失败')
        data['user']['comments_likeds']=[]
        for comment_like in comment_likeds:
            data['user']['comments_likeds'].append(comment_like.comment_id)
    data['comments']=[]
    for comment in comments:
        comment_dict=comment.to_dict()
        if data['user']:
            if comment_dict['id'] in data['user']['comments_likeds']:
                comment_dict['is_like']=True
                #print(comment_dict['id'])
        data['comments'].append(comment_dict)
    return render_template('news/detail.html',data=data)

@news_blu.route('/news_comment',methods=['POST'])
def news_comment():
    from information.utils.models import Comment,User
    from information import db
    if not data['user']:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    params_dict=request.json
    news_id = params_dict.get('news_id')
    comment = params_dict.get('comment')
    parent_id = params_dict.get('parent_id')
    if not all([news_id,comment]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')
    if parent_id:
        try:
            comment_input = Comment(user_id=data['user']['id'], news_id=int(news_id), content=comment,parent_id=int(parent_id))
            db.session.add(comment_input)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库插入数据失败')
    else:
        try:
            comment_input=Comment(user_id=data['user']['id'],news_id=int(news_id),content=comment)
            db.session.add(comment_input)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库插入数据失败')
    data['comment']=comment_input.to_dict()
    data['comment']['user']=data['user']
    #print(data['comment'])
    return jsonify(errno=RET.OK, errmsg='评论成功',data=data['comment'])

@news_blu.route('/comment_like',methods=['POST'])
def comment_like():
    from information.utils.models import Comment,CommentLike
    from information import db
    if not data['user']:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    params_dict = request.json
    comment_id = params_dict.get('comment_id')
    action = params_dict.get('action')
    if not all([comment_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')
    try:
        if action=='add':
            comment=Comment.query.filter_by(id=int(comment_id)).first()
            comment.like_count+=1
            db.session.add(comment)
            comment_liked=CommentLike(user_id=data['user']['id'],comment_id=int(comment_id))
            db.session.add(comment_liked)
            #print(comment_liked)
            db.session.commit()
        elif action=='remove':
            comment = Comment.query.filter_by(id=int(comment_id)).first()
            comment.like_count -= 1
            db.session.add(comment)
            comment_liked = CommentLike.query.filter_by(user_id=data['user']['id'],comment_id=int(comment_id)).first()
            db.session.delete(comment_liked)
            db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据更新失败')
    return jsonify(errno=RET.OK, errmsg='请求成功')

@news_blu.route('/news_collect',methods=['POST'])
def news_collect():
    from information.utils.models import User,News
    from information import db
    if not data['user']:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    params_dict = request.json
    news_id = params_dict.get('news_id')
    action = params_dict.get('action')
    if not all([news_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')
    if action=='collect':
        try:
            user=User.query.filter_by(id=data['user']['id']).first()
            collection_news=user.collection_news
            news=News.query.filter_by(id=news_id).first()
            collection_news.append(news)
            db.session.add(user)
            db.session.commit()
            data['is_collected']=True
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='新闻收藏失败')
    elif action=='cancel_collect':
        try:
            user=User.query.filter_by(id=data['user']['id']).first()
            collection_news=user.collection_news
            news=News.query.filter_by(id=news_id).first()
            collection_news.remove(news)
            db.session.add(user)
            db.session.commit()
            data['is_collected']=False
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='新闻取消收藏失败')
    return jsonify(errno=RET.OK, errmsg='新闻收藏成功')

@news_blu.route('/followed_user',methods=['POST'])
def followed_user():
    if not data['user']:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登陆')
    from information.utils.models import User
    from information import db
    params_dict = request.json
    user_id = int(params_dict.get('user_id'))
    action = params_dict.get('action')
    if action=='follow':
        try:
            user = User.query.filter_by(id=data['user']['id']).first()
            author=User.query.filter_by(id=user_id).first()
            author.followers.append(user)
            db.session.add(author)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='关注失败')
    elif action=='unfollow':
        try:
            user = User.query.filter_by(id=data['user']['id']).first()
            author=User.query.filter_by(id=user_id).first()
            author.followers.remove(user)
            db.session.add(author)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='取消关注失败')
    return jsonify(errno=RET.OK, errmsg='关注成功')